// 1)导入http模块
let http = require("http");
let https = require("https");
let url = require("url");
const cheerio = require("cheerio"); //引入cheerio

// 2)创建web服务器实例
const server = http.createServer();

// 3)为服务器实例绑定request事件，监听客户端请求
server.on("request", (req, res) => {
  const urlObj = url.parse(req.url, true);

  res.writeHead(200, {
    //跨域(xxx策略不允许)
    "Access-Control-Allow-Origin": "*", //允许所有源访问
    "content-type": "application/json;text/plain;charset=utf-8",
  });

  if (urlObj.pathname === "/api/getInfo") {
    httpget((data) => res.end(spider(data)));
  } else {
    res.end("404 Not Found");
  }
});

// https://i.maoyan.com/#movie
function httpget(cp) {
  let data = "";
  https.get("https://i.maoyan.com", (res) => {
    res.on("data", (chunk) => {
      // 监听response的状态，如果状态一直是data，说明还在接收数据,chunk数据片段
      data += chunk;
    });
    res.on("end", () => {
      // 监听response的状态，如果状态变成了end，说明数据接收完毕
      console.log(data);
      cp(data);
    });
  });
}

function spider(data) {
  const $ = cheerio.load(data);
  let $movieList = $(".column.content");
  let movies = [];
  $movieList.each((index, item) => {
    movies.push({
      title: $(value).find(".title").text(),
      grade: $(value).find(".grade").text(),
      actor: $(value).find(".actor").text(),
    });
  });
  console.log(movies);
  return JSON.stringify(movies);
}

server.listen(80, () => {
  console.log("http://127.0.0.1");
});
